package com.example.im.ui.fragment

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.example.im.xmpp.IMConnection
import com.example.im.R
import com.example.im.app.ImApplication
import com.example.im.bean.EventBusData
import com.example.im.common.Constants
import com.example.im.common.Enumerate
import com.example.im.http.APIRetrofit
import com.example.im.http.RetrofitManager
import com.example.im.manager.ActivityCollector
import com.example.im.ui.activity.AccessActivity
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.db.DatabaseStorage
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_main_mine.*
import org.greenrobot.eventbus.EventBus


class MainMineFragment : AbstractBaseFragment<BasePresenter<*>>(), View.OnClickListener {


    companion object {
        fun newInstance(): MainMineFragment {
            return MainMineFragment()
        }
    }

    override val layoutId: Int
        get() = R.layout.fragment_main_mine

    override fun initView() {

        val account = DatabaseStorage.getAccountInfoStorage()
        tv_account_name.text = account.name
        tv_account_user_name.text = account.username

        tv_account_cut.setOnClickListener(this)
        tv_account_exit.setOnClickListener(this)
        tv_account_clear_chat.setOnClickListener(this)
        tv_account_invite.setOnClickListener(this)
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    override fun onClick(v: View?) {

        when (v!!.id) {
            R.id.tv_account_cut -> {
                val dialog = AlertDialog.Builder(activity!!)
                dialog.setMessage("是否切换账号")
                dialog.setPositiveButton("确定") { d, _ ->
                    d.cancel()
                    IMConnection.instance!!.connectQuit()
                    val preferences = activity!!
                        .getSharedPreferences(Constants.ACCOUNT_ATTRIBUTES, Context.MODE_PRIVATE)
                    preferences.edit().remove(Constants.ACCOUNT_PASSWORDS).apply()
                    activity!!.startActivity(Intent(activity, AccessActivity::class.java))
                    activity!!.finish()
                }
                dialog.setNegativeButton("取消", null)
                dialog.show()
            }
            R.id.tv_account_exit -> {
                val dialog = AlertDialog.Builder(activity!!)
                dialog.setMessage("是否退出")
                dialog.setPositiveButton("确定") { d, _ ->
                    d.cancel()
                    IMConnection.instance!!.connectQuit()
                    ActivityCollector.finishAll()
                }
                dialog.setNegativeButton("取消", null)
                dialog.show()
            }
            R.id.tv_account_invite -> {
                if (tv_account_user_name.text.isEmpty()) {
                    return
                }
                Observable.just(mapOf("login" to tv_account_user_name.text.toString()))
                    .subscribeOn(Schedulers.io())
                    .flatMap {
                        RetrofitManager.retrofit().create(APIRetrofit::class.java)
                            .setInviteCode(it)
                    }
                    .filter {
                        if (it.code != 0 || it.data == null) {
                            onHint("生成邀请码失败")
                        }
                        it.code == 0 && it.data != null
                    }
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        val dialog = AlertDialog.Builder(activity!!)
                        dialog.setTitle("邀请码")
                        dialog.setMessage(it.data.toString())
                        dialog.setPositiveButton("分享") { d, _ ->
                            d.cancel()
                            var shareIntent = Intent()
                            shareIntent.action = Intent.ACTION_SEND
                            shareIntent.type = "text/plain"
                            shareIntent.putExtra(
                                Intent.EXTRA_TEXT,
                                "#Windows下载链接#http://101.37.253.11/IMVOC_WINDOWS.exe 打开此链接下载\n#Android下载链接#http://101.37.253.11/IMVOC_ANDROID.apk 打开此链接下载\n#注册邀请码#${it.data}"
                            )
                            shareIntent =
                                Intent.createChooser(shareIntent, "发送至...")
                            startActivity(shareIntent)
                        }
                        dialog.setNegativeButton("复制") { d, _ ->
                            d.cancel()
                            val cm = activity!!.getSystemService(Context.CLIPBOARD_SERVICE)
                                    as ClipboardManager
                            val cd = ClipData.newPlainText(
                                "Label",
                                "#Windows下载链接#http://101.37.253.11/IMVOC_WINDOWS.exe 打开此链接下载\n#Android下载链接#http://101.37.253.11/IMVOC_ANDROID.apk 打开此链接下载\n#注册邀请码#${it.data}"
                            )
                            cm.primaryClip = cd
                        }
                        dialog.show()
                    }, {
                        onHint("${it.message}")
                    })
            }
            R.id.tv_account_clear_chat -> {
                val dialog = AlertDialog.Builder(activity!!)
                dialog.setMessage("是否清空所有聊天记录")
                dialog.setPositiveButton("确定") { _, _ ->
                    ImApplication.appDatabase().chatRecordDao().delete()
                    val data = EventBusData<Any>(
                        Enumerate.Handle.list_chat, Enumerate.Action.list_clear, "delete"
                    )
                    EventBus.getDefault().post(data)
                }
                dialog.setNegativeButton("取消", null)
                dialog.show()
            }
        }
    }
}